﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;

public partial class MasterPages_Default : System.Web.UI.Page
{
    private HttpCookie cookies;
    protected void Page_Load(object sender, EventArgs e)
    {
        cookies = Request.Cookies["Acount"];
        if (cookies == null)
        {
            cookies = new HttpCookie("Acount");
            cookies.Expires = DateTime.Now.AddDays(1);
            cookies["Failed"] = "0";
            Response.Cookies.Add(cookies);
        }
        if (IsPostBack)
        {
            //cookies = Request.Cookies["Acount"];
            //int fail = int.Parse(cookies["Failed"]);
            //if ((fail >= 3) && (!custValidatorCapcha.Enabled))
            //{
            //    divCapcha.Style.Remove(HtmlTextWriterStyle.Display);
            //    divCapcha.Style.Add(HtmlTextWriterStyle.Display, "block");
            //    custValidatorCapcha.Enabled = true;
            //}
            OpenIdRelyingParty openid = new OpenIdRelyingParty();
            var str = openid.GetResponse();
            if (str != null)
            {

                switch (str.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        //NotLoggedIn.Visible = false;
                        var fetch = str.GetExtension<FetchResponse>();
                        string email = "";
                        if (fetch != null)
                        {
                            AcountDTO acount = new AcountDTO();
                            acount.IsOpenID = true;
                            acount.FirstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First + " " + WellKnownAttributes.Name.Middle);
                            acount.LastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                            acount.Email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                            acount.Phone = fetch.GetAttributeValue(WellKnownAttributes.Contact.Phone.Home + "," + WellKnownAttributes.Contact.Phone.Mobile + "," + WellKnownAttributes.Contact.Phone.Work);
                            string address = WellKnownAttributes.Contact.HomeAddress.StreetAddressLine1 + "," + WellKnownAttributes.Contact.HomeAddress.StreetAddressLine2 + "," + WellKnownAttributes.Contact.HomeAddress.City + "," + WellKnownAttributes.Contact.HomeAddress.Country;
                            address = address.Replace(",,", ",").Replace(",,", ",");
                            acount.Address = address;
                            acount.Website = fetch.GetAttributeValue(WellKnownAttributes.Contact.Web.Blog);
                            Session["Acount"] = acount;                            
                        }
                        Response.Redirect("Home.aspx");
                        break;
                    case AuthenticationStatus.Canceled:
                        break;
                    case AuthenticationStatus.Failed:
                        break;
                }
            }

        }
        else
        {
            if (cookies["acount"] != null && 0 < DBAccess.checkAcount(cookies["acount"], cookies["pass"]))
            {
                Session["Acount"] = DBAccess.getAcount(cookies["acount"]);
                Response.Redirect("Home.aspx");
            }
            else
                divInfo.InnerHtml = MyFunction.getXSLT(Server.MapPath("../XmlFiles/Login.xml"), Server.MapPath("../XmlFiles/LoginPage.xslt"));
        }
    }
    protected void custValidatorCapcha_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (tbMaAnToan.Value.ToLower() == Session["capcha"].ToString())
            args.IsValid = true;
        else
            args.IsValid = false;
    }
    protected void custValidatorLogin_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if(0<DBAccess.checkAcount(tbTenDangNhap.Value, MyFunction.MahoaMatKhau(tbMatKhau.Value)))
            args.IsValid = true;
        else
            args.IsValid = false;
    }
    protected void btnOpenID_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            ImageButton btn = (ImageButton)sender;
            string str = btn.CommandArgument.ToString();
            OpenIdRelyingParty openID = new OpenIdRelyingParty();
            IAuthenticationRequest request = openID.CreateRequest(str);
            var fetch = new FetchRequest();
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.Email);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.HomeAddress.City);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Contact.HomeAddress.Country);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Name.FullName);
            fetch.Attributes.AddRequired(DotNetOpenAuth.OpenId.Extensions.AttributeExchange.WellKnownAttributes.Company.CompanyName);
            request.AddExtension(fetch);            
            request.RedirectToProvider();
        }
        catch (System.ServiceModel.ProtocolException ex) { }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        cookies["Failed"] = "0";
        if (!Page.IsValid)
        {
            int fail = int.Parse(cookies["Failed"]);
            cookies["Failed"] = (fail += 1).ToString();
            Response.Cookies.Add(cookies);
            if (fail == 3)
            {
                divCapcha.Style.Remove(HtmlTextWriterStyle.Display);
                divCapcha.Style.Add(HtmlTextWriterStyle.Display, "block");
                custValidatorCapcha.Enabled = true;
            }
        }
        else
        {
            cookies["Failed"] = "0";
            Response.Cookies.Add(cookies);
            if (rememberme.Checked)
            {
                cookies["acount"] = tbTenDangNhap.Value;
                cookies["pass"] = MyFunction.MahoaMatKhau(tbMatKhau.Value);
            }
            AcountDTO acount = DBAccess.getAcount(tbTenDangNhap.Value);
            Session["Acount"] = acount;          
            Response.Redirect("Home.aspx");
        }
    }
}